package com.app.conrtoller;

import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.hsy.*;
import com.app.domain.xygs.YajiangData;
import com.app.domain.xygs.YajiangDetailData;
import com.app.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

// S46长兴至高淳高速公路宣城段,1标1号站
@Slf4j
@RestController
@RequestMapping("/xygs")
public class XygsUploadController {
    @Value("${yj.xygstj02yzc01.serviceHost}")
    private String serviceHost;
    
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    XygsService uploadService;
    @Autowired
    SendMessageService sendMessageService;

    // 常量定义
    private static final String UPLOAD_PARAMETER_ID = "46";
    private static final String SWYJSY_M_TYPE = "SWYJSY_M";
    private static final String SWYJSY_S_TYPE = "SWYJSY_S";
    private static final String SWYJSY_S_S_TYPE = "SWYJSY_S_S";

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids,@RequestParam(value = "uploadId") String uploadId, @RequestParam(value = "sbbh") String sbbh) {
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuilder responseContent = new StringBuilder();
        responseContent.append("本次共上传数据：【").append(total).append("】条,");

        try {
            for (String id : ids) {
                try {
                    if (handleUpload(id, uploadId, sbbh)) {
                        succTotal++;
                    } else {
                        failTotal++;
                    }
                } catch (Exception e) {
                    log.error("处理ID={}时发生异常: {}", id, e.getMessage(), e);
                    updateState("0", id);
                    failTotal++;
                }
            }
        } catch (Exception e) {
            log.error("批量上传过程中发生异常: {}", e.getMessage(), e);
        }

        responseContent.append("成功【").append(succTotal).append("】条,失败").append(failTotal).append("条");
        return new ExternalResponse(0, responseContent.toString(), "");
    }

    private boolean handleUpload(String id, String uploadId, String sbbh) throws Exception {
        YjData yjData = yjDataService.findOne(id);
        if (yjData == null) {
            log.warn("ID={}对应的YjData不存在", id);
            return false;
        }

        UploadParameter uploadParameter = uploadParameterService.findOne(uploadId);
        if (uploadParameter == null) {
            log.warn("ID={}对应的UploadParameter不存在", uploadId);
            return false;
        }

        String uuid = sendMessageService.ConditionQuery(id);
        if (StringUtils.isEmpty(uuid)) {
            return handleNewUpload(yjData, uploadParameter, sbbh);
        } else {
            return handleExistingUpload(yjData, uploadParameter, uuid, sbbh);
        }
    }

    private boolean handleNewUpload(YjData yjData, UploadParameter uploadParameter, String sbbh) throws Exception {
        List<YajiangData> yjsy_mList = uploadService.getYajiangData(yjData, uploadParameter, sbbh);
        ResponseResult mResult = uploadService.sendHsyMessage(SWYJSY_M_TYPE, serviceHost, yjsy_mList);
        if (!isSuccess(mResult)) {
            log.info("ID={}的SWYJSY_M数据发送失败", yjData.getId());
            return false;
        }

        SendMessage sendMessage = createSendMessage(yjData, yjsy_mList.get(0).getSyjid());
        sendMessageService.insert(sendMessage);

        List<YajiangDetailData> yjsy_sList = uploadService.getYajiangDetailData(yjData, uploadParameter, yjsy_mList.get(0).getSyjid());
        ResponseResult sResult = uploadService.sendHsyMessage(SWYJSY_S_TYPE, serviceHost, yjsy_sList);
        if (!isSuccess(sResult)) {
            log.info("ID={}的SWYJSY_S数据发送失败", yjData.getId());
            return false;
        }

     /*   List<Yjsy_S_S> yjsy_s_sList = uploadService.getYjsy_S_S(yjData, uploadParameter, yjsy_sList.get(0).getHoleid(), sbbh);
        ResponseResult ssResult = uploadService.sendHsyMessage(SWYJSY_S_S_TYPE, serviceHost, yjsy_s_sList);
        if (!isSuccess(ssResult)) {
            log.info("ID={}的SWYJSY_S_S数据发送失败", yjData.getId());
            return false;
        }*/

        updateState("1", String.valueOf(yjData.getId()));
        return true;
    }

    private boolean handleExistingUpload(YjData yjData, UploadParameter uploadParameter, String uuid, String sbbh) throws Exception {
        List<YajiangDetailData> yjsy_sList = uploadService.getYajiangDetailData(yjData, uploadParameter, uuid);
        ResponseResult sResult = uploadService.sendHsyMessage(SWYJSY_S_TYPE, serviceHost, yjsy_sList);
        if (!isSuccess(sResult)) {
            log.info("ID={}的SWYJSY_S数据发送失败", yjData.getId());
            return false;
        }

  /*      List<Yjsy_S_S> yjsy_s_sList = uploadService.getYjsy_S_S(yjData, uploadParameter, yjsy_sList.get(0).getHoleid(), sbbh);
        ResponseResult ssResult = uploadService.sendHsyMessage(SWYJSY_S_S_TYPE, serviceHost, yjsy_s_sList);
        if (!isSuccess(ssResult)) {
            log.info("ID={}的SWYJSY_S_S数据发送失败", yjData.getId());
            return false;
        }*/

        updateState("1", String.valueOf(yjData.getId()));
        return true;
    }

    private boolean isSuccess(ResponseResult result) {
        return result != null && result.getSendCount().equals(result.getSuccCount());
    }

    private SendMessage createSendMessage(YjData yjData, String syjid) {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setSbbh(yjData.getDevice_code());
        sendMessage.setLh(yjData.getBridge_code());
        sendMessage.setKh(yjData.getDuct_code());
        sendMessage.setBusi_type(SWYJSY_M_TYPE);
        sendMessage.setUpload_time(new Date());
        sendMessage.setUuid(syjid);
        sendMessage.setStatus("0");
        return sendMessage;
    }


    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}
